
using System;

namespace WindowsFormsApplication1
{


	public class DTW2
	{

		private int[] template;
		
		public DTW2 (int[] temp)
		{
			defineTemplate(temp);
		}
		
		public int calcularDistancia( int[] amostra)
		{
		
			int a = 1;
			int t = 1;
			int r = 6;
			int [,] DTW = new int[amostra.Length,template.Length];
			int referencia  = amostra[amostra.Length/2];
			bool flag = true;
			int dist = 0;
			
			for(int i = 0 ; i < template.Length ; i++)
				DTW[0,i] = 0;
			
			for(int i = 0 ; i < amostra.Length ; i++)
				DTW[i,0] = 0;
			
			DTW[1,1] = 2*custo(1,1);
			a++;
			
			while(flag)
			{
				if(a > t+r)
				{
					t++;
					if(t == template.Length -1){
						flag = false;
					}
					else
						a = t - r;
				}
				else
				{
					if(a > 0 && a < amostra.Length){
						int c = custo(amostra[a]-referencia,template[t]);
						DTW[a,t]=Math.Min(Math.Min(DTW[a,t-1]+c,DTW[a-1,t]+c),DTW[a-1,t-1]+2*c);
					}
					a++;
				}
			}
			
			dist = DTW[amostra.Length-2,template.Length-2]/(amostra.Length+template.Length);
 			Console.Write(dist.ToString()+"\n");
			if(dist<1000000)
				defineTemplate(amostra);
			
			amostra = null;
			return (int) dist;
		
		}
		
		private int custo(int t, int l)
		{
			return (t-l)*(t-l);
		}
		
	
		private void defineTemplate(int[] amostra)
		{
			int referencia = amostra[amostra.Length/2];
			
			for(int i = 0 ; i< amostra.Length ; i++)
				amostra[i] = amostra[i] - referencia;
			
			this.template = amostra;
		}
	
	}
}
